package com.fly.core.exception;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.fly.core.entity.AjaxObject;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler
{
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    String handleException(MethodArgumentNotValidException exception)
    {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        List<String> errMsg = new ArrayList<>();
        for (FieldError error : fieldErrors)
        {
            errMsg.add(error.getDefaultMessage());
        }
        Collections.sort(errMsg);
        return AjaxObject.newError(StringUtils.join(Arrays.asList(errMsg), ",")).toString();
    }
}